// Utility for preloading images

// List of login modal images to preload
const loginModalImages = [
  'https://www.knomi.me/aiImgas/1.webp',
  'https://www.knomi.me/aiImgas/2.webp',
  'https://www.knomi.me/aiImgas/3.webp',
  'https://www.knomi.me/aiImgas/4.webp',
  'https://www.knomi.me/aiImgas/5.webp',
  'https://www.knomi.me/aiImgas/6.webp',
  'https://www.knomi.me/aiImgas/7.webp',
  'https://www.knomi.me/aiImgas/8.webp',
  'https://www.knomi.me/aiImgas/loginguys_1.jpg',
  'https://www.knomi.me/aiImgas/loginguys_2.jpg',
  'https://www.knomi.me/aiImgas/loginGirl_1.jpg',
  'https://www.knomi.me/aiImgas/loginGirl_2.png',
  'https://www.knomi.me/resource_AiPersion/G8/694be879-6fe9-479d-9103-af0a0998fa60.webp',
  'https://www.knomi.me/resource_AiPersion/G8/fb0c0ced-8788-4733-b9ce-39ac78075dd8.webp'
];

// Flag to track if preloading has been done
let imagesPreloaded = false;

// 存储所有预渲染的背景图片元素
const prerenderedBackgrounds: { [key: string]: HTMLDivElement } = {};

/**
 * 提前创建所有可能的背景图片DOM元素
 */
export const prerenderBackgroundElements = (): void => {
  if (document.getElementById('prerendered-backgrounds')) return;

  // console.log('🖼️ 预渲染登录模态框背景...');

  // 创建容器
  const container = document.createElement('div');
  container.id = 'prerendered-backgrounds';
  container.style.position = 'absolute';
  container.style.left = '-9999px';
  container.style.top = '-9999px';
  container.style.opacity = '0';
  container.style.visibility = 'hidden';
  container.style.pointerEvents = 'none';

  // 添加到DOM
  document.body.appendChild(container);

  // 创建所有可能的背景组合
  loginModalImages.forEach(img => {
    const key = img.split('/').pop()?.split('.')[0] || '';

    const bgElement = document.createElement('div');
    bgElement.className = 'prerendered-background';
    bgElement.style.width = '500px';
    bgElement.style.height = '600px';
    bgElement.style.backgroundImage = `url(${img})`;
    bgElement.style.backgroundSize = 'cover';
    bgElement.style.backgroundPosition = 'center';

    // 保存到全局对象
    prerenderedBackgrounds[img] = bgElement;

    // 添加到容器
    container.appendChild(bgElement);
  });

  // console.log('✅ 背景预渲染完成');
};

/**
 * 获取预渲染的背景样式
 */
export const getPrerenderedBackground = (url: string): string => {
  // 如果存在预渲染的元素，返回唯一ID
  if (prerenderedBackgrounds[url]) {
    return url;
  }
  return '';
};

/**
 * Preloads all login modal images
 * @returns Promise that resolves when all images are loaded or rejects if any fails
 */
export const preloadLoginImages = (): Promise<void> => {
  // If images already preloaded, return resolved promise
  if (imagesPreloaded) {
    return Promise.resolve();
  }

  // console.log('🖼️ Preloading login modal images...');

  // Create array of image loading promises
  const imagePromises = loginModalImages.map(src => {
    return new Promise<void>((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => {
        console.warn(`Failed to preload image: ${src}`);
        resolve(); // Resolve anyway to not block others
      };
      img.src = src;
    });
  });

  // Return a promise that resolves when all images are loaded
  return Promise.all(imagePromises)
    .then(() => {
      // console.log('✅ Login modal images preloaded successfully');
      imagesPreloaded = true;

      // 完成图片预加载后，进行预渲染
      if (typeof document !== 'undefined') {
        setTimeout(prerenderBackgroundElements, 300);
      }
    })
    .catch(error => {
      console.error('❌ Error preloading login modal images:', error);
      throw error;
    });
};

// Export the list of images for reference
export const getLoginModalImages = () => [...loginModalImages]; 